package com.rc.saas.tenant.controller.finance;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.constant.CommonConstant;
import com.rc.saas.tenant.common.utils.DateHelper;
import com.rc.saas.tenant.common.utils.DateUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.rc.RcOperatorAccount;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.rc.RcOperatorAccountSearch;
import com.rc.saas.tenant.service.rc.RcOperatorAccountService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

/**
 * 加盟商结算列表控制器
 * @author quankl
 */
@Controller
@RequestMapping("/operatorAccount")
public class RcOperatorAccountController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(RcOperatorAccountController.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private RcOperatorAccountService rcOperatorAccountService;

    @Autowired
    private TenantRoleService tenantRoleService;

    /**
     * 跳转 加盟商结算列表
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/operatorAccount/index";
    }

    /**
     * 跳转 加盟商结算详情页面
     */
    @RequestMapping(value = "/detail/{operatorAccountId}", method = RequestMethod.GET)
    public String editRcOperatorAccount(Model model, @PathVariable("operatorAccountId") Long operatorAccountId) {
        RcOperatorAccount operatorAccount = rcOperatorAccountService.selectByPrimaryKey(operatorAccountId);
        model.addAttribute("operatorAccount", operatorAccount);
        model.addAttribute("payTimeStart", DateUtil.formatDateTime(DateUtil.getLastMonthStart()));
        model.addAttribute("payTimeEnd", DateUtil.formatDateTime(DateUtil.getLastMonthEnd()));

        Calendar instance = Calendar.getInstance();
        instance.setTime(operatorAccount.getCreatedTime());
        instance.set(Calendar.DAY_OF_MONTH,1);
        instance.set(Calendar.HOUR_OF_DAY,0);
        instance.set(Calendar.MINUTE,0);
        instance.set(Calendar.SECOND,0);
        Date endTime = instance.getTime();

        model.addAttribute("endTime", DateHelper.dataToString(endTime,DateHelper.DATE_COMMON_FORMAT));

        instance.add(Calendar.MONTH,-1);
        Date startTime = instance.getTime();

        model.addAttribute("startTime", DateHelper.dataToString(startTime,DateHelper.DATE_COMMON_FORMAT));

        return "/templates/operatorAccount/detail";
    }


    /**
     * 加盟商结算列表分页数据
     */
    @ResponseBody
    @RequestMapping(value = "/listPageData", method = RequestMethod.GET)
    public WebPageInfo listPageData(RcOperatorAccountSearch rcOperatorAccountSearch) {
        //获取登陆人信息
        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole role = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        if (null == user || null == role || "3".equals(role.getRoleType())) {
            PageInfo<RcOperatorAccount> pageInfo = new PageInfo<>();
            WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
            return webPageInfo;
        }
        String dataAuth = role.getDataAuth();//数据权限 100 平台权限, 010 加盟商权限,001企业权限,111全部权限 默认111 不能为000
        String roleType = role.getRoleType();//角色类型 ( 0 超级管理员 1 普通用户 2加盟商 3企业用户) 默认1`
        rcOperatorAccountSearch.setDataAuth(dataAuth);
        rcOperatorAccountSearch.setRoleType(roleType);
        rcOperatorAccountSearch.setBaseOperatorId(user.getOperatorId());

        PageInfo<RcOperatorAccount> pageInfo = rcOperatorAccountService.listPageByCondition(rcOperatorAccountSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 结算操作
     */
    @ResponseBody
    @RequestMapping(value = "/settlement", method = RequestMethod.POST)
    public TResponse settlement(Long operatorAccountId) {
        TenantUser user = ShiroUtils.getSessionUser();
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        try {
            RcOperatorAccount operatorAccount = rcOperatorAccountService.selectByPrimaryKey(operatorAccountId);
            if(!Objects.isNull(operatorAccount)){
                operatorAccount.setStatus("1");//0:未结算，1:结算通过，2:结算驳回
                operatorAccount.setLastUpdatedBy(tenant.getLoginName());
                operatorAccount.setLastUpdatedTime(new Date());
                operatorAccount.setFinishTime(new Date());
                int rows = rcOperatorAccountService.updateByPrimaryKey(operatorAccount);
                if(rows>0){
                    return TResponse.SUCCESS();
                }
            }
            return TResponse.FAIL();
        }catch (Exception e){
            logger.error("结算操作发生异常", e);
            return TResponse.FAIL(CommonConstant.MSG_EXCEPTION);
        }

    }

    /**
     * 导出加盟商结算列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(RcOperatorAccountSearch rcOperatorAccountSearch, HttpServletResponse response) {
        try {
            //获取登陆人信息
            TenantUser user = ShiroUtils.getSessionUser();
            TenantRole role = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
            String dataAuth = role.getDataAuth();//数据权限 100 平台权限, 010 加盟商权限,001企业权限,111全部权限 默认111 不能为000
            String roleType = role.getRoleType();//角色类型 ( 0 超级管理员 1 普通用户 2加盟商 3企业用户) 默认1`
            rcOperatorAccountSearch.setDataAuth(dataAuth);
            rcOperatorAccountSearch.setRoleType(roleType);
            rcOperatorAccountSearch.setBaseOperatorId(user.getOperatorId());

            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(rcOperatorAccountSearch);
            PageInfo<RcOperatorAccount> pageInfo = rcOperatorAccountService.listPageByCondition(rcOperatorAccountSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("加盟商结算列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcOperatorAccount.class).sheet("加盟商结算列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出加盟商结算列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }
}
